package cn.flying.cloud.file.web;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.flying.cloud.base.common.exception.BizException;
import cn.flying.cloud.base.common.utils.Ft;
import cn.flying.cloud.base.common.vo.Rt;
import cn.flying.cloud.file.core.service.FileService;
import cn.flying.cloud.file.model.FileRequest;

/**
 * 文件操作相关请求处理服务
 *
 * @author: admin
 * @date: 2025年07月14日 14:33
 * @version: 1.0
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private FileService fileService;

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Rt<?> upload(@RequestParam("file") MultipartFile file, @RequestParam("bucket") String bucketName, String serviceCode) throws IOException {
        FileRequest req = new FileRequest();
        req.setTenantId(Ft.Local.TenantId());
        req.setRequestNo(UUID.randomUUID().toString().replaceAll("-", ""));
        if (Ft.String.isBlank(serviceCode)) {
            serviceCode = "default";
        }
        req.setServiceCode(serviceCode);
        req.setBucketName(bucketName);
        req.setFileName(file.getOriginalFilename());
        req.setContent(file.getBytes());

        String path = fileService.uploadFile(req);

        return Rt.success("上传成功", path);
    }

    @RequestMapping("/download")
    public void download(@RequestParam("bucket") String bucket, @RequestParam("filename") String filename, HttpServletResponse response) {
        try (OutputStream outputStream = response.getOutputStream()) {
//        String tenantId = Ft.Local.TenantId();
            byte[] bytes = fileService.download(bucket, filename);
            outputStream.write(bytes);
        } catch (Exception e) {
            throw new BizException("下载失败", e);
        }
    }

    /**
     * 获取文件的预览url
     *
     * @param bucket
     * @param filename
     * @return
     */
    @GetMapping("/getObjectUrl")
    public Rt<?> getObjectUrl(String bucket, String filename) {
        String url = fileService.getObjectUrl(bucket, filename);
        return Rt.success("成功", url);
    }
}
